﻿<!DOCTYPE html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<html>
<body>
	<jsp:include page="frame.jsp" />
	<div class="main-content">
		<div class="main-content-inner">
			<div class="breadcrumbs ace-save-state" id="breadcrumbs">
				<ul class="breadcrumb">
					<li>
						<i class="ace-icon fa fa-home home-icon"></i>
						<a href="${pageContext.request.contextPath}/statistics">首页</a>
					</li>
					<li class="active">网站综合管理</li>
				</ul><!-- /.breadcrumb -->

				<div class="nav-search" id="nav-search">
					<form class="form-search" action="#">
						<span class="input-icon">
							<input type="text" placeholder="搜索" class="nav-search-input" id="nav-search-input" autocomplete="off" />
							<i class="ace-icon fa fa-search nav-search-icon"></i>
						</span>
					</form>
				</div><!-- /.nav-search -->
			</div>

			<div class="page-content">
				<div class="page-header">
					<h1>
						网站综合管理
						<small>
							<i class="ace-icon fa fa-angle-double-right"></i>
							统计数据一览
						</small>
					</h1>
				</div><!-- /.page-header -->

				<div class="row">
					<div class="col-xs-12">
						<!-- PAGE CONTENT BEGINS -->
						<div class="row">
							<div class="space-6"></div>

							<div class="col-sm-7 infobox-container">

								<div class="infobox infobox-green  ">
									<div class="infobox-icon">
										<img width="32" src="${pageContext.request.contextPath}/asserts/backstage/img/icon_product.png"/>
									</div>
									<div class="infobox-data">
										<span class="infobox-data-number" id="productCount">0</span>
										<div class="infobox-content">商品数</div>
									</div>
								</div>


								<div class="infobox infobox-blue  ">
									<div class="infobox-icon">
										<img width="32" src="${pageContext.request.contextPath}/asserts/backstage/img/icon_category.png"/>
									</div>

									<div class="infobox-data">
										<span class="infobox-data-number" id="categoryCount">0</span>
										<div class="infobox-content">分类数</div>
									</div>
								</div>

								<div class="infobox infobox-green  ">
									<div class="infobox-icon">
										<img width="32" src="${pageContext.request.contextPath}/asserts/backstage/img/icon_user.png"/>
									</div>

									<div class="infobox-data">
										<span class="infobox-data-number" id="userCount">0</span>
										<div class="infobox-content">用户数</div>
									</div>
								</div>

								<div class="infobox infobox-pink  ">
									<div class="infobox-icon">
										<img width="32" src="${pageContext.request.contextPath}/asserts/backstage/img/icon_browse.png"/>
									</div>

									<div class="infobox-data">
										<span class="infobox-data-number" id="browseCount">0</span>
										<div class="infobox-content">商品浏览次数</div>
									</div>
								</div>

								<div class="infobox infobox-blue2  ">
									<div class="infobox-icon">
										<img width="32" src="${pageContext.request.contextPath}/asserts/backstage/img/icon_order.png"/>
									</div>

									<div class="infobox-data">
										<span class="infobox-data-number" id="orderCount">0</span>
										<div class="infobox-content">订单数</div>
									</div>
								</div>

								<div class="space-6"></div>

							</div>

							<div class="col-sm-5">
								<div class="widget-box">
									<div class="widget-header widget-header-flat widget-header-small">
										<h5 class="widget-title">
											<i class="ace-icon fa fa-signal"></i>
											商品分类占比
										</h5>
									</div>

									<div class="widget-body">
										<div class="widget-main">
											<div id="piechart-placeholder"></div>
										</div><!-- /.widget-main -->
									</div><!-- /.widget-body -->
								</div><!-- /.widget-box -->
							</div><!-- /.col -->
						</div><!-- /.row -->

						<div class="hr hr32 hr-dotted"></div>

						<div class="row">
							<div class="col-sm-5">
								<div class="widget-box transparent">
									<div class="widget-header widget-header-flat">
										<h4 class="widget-title lighter">
											<i class="ace-icon fa fa-star orange"></i>
											热门商品
										</h4>

										<div class="widget-toolbar">
											<a href="#" data-action="collapse">
												<i class="ace-icon fa fa-chevron-up"></i>
											</a>
										</div>

										<div class="widget-toolbar">
											<!-- 选项卡组件（菜单项nav-tabs）-->
											<ul class="nav nav-tabs" role="tablist">
												<li>
													<a href="#hot" role="tab" data-toggle="tab">最热</a>
												</li>
												<li class="active">
													<a href="#new" role="tab" data-toggle="tab">最新</a>
												</li>
											</ul>
										</div>
									</div>

									<div class="widget-body">
										<div class="tab-content">
											<div class="tab-pane active" id="new">
												<div class="widget-main no-padding">
													<table class="table table-bordered table-striped" style="table-layout:fixed">
														<thead class="thin-border-bottom">
														<tr>
															<th>
																<i class="ace-icon fa fa-caret-right blue"></i>商品图片
															</th>

															<th>
																<i class="ace-icon fa fa-caret-right blue"></i>商品名称
															</th>

															<th class="hidden-480">
																<i class="ace-icon fa fa-caret-right blue"></i>发布时间
															</th>

															<th>
																<i class="ace-icon fa fa-caret-right blue"></i>浏览量
															</th>
														</tr>
														</thead>

														<tbody>
															<c:forEach items="${newestProducts}" var="p" end="4">
																<tr>
																	<td style="text-align: center;"><img width="32" src="${pageContext.request.contextPath}/${p.pimage}" alt="${p.pimage}"></td>
																	<td style="overflow:hidden;white-space:nowrap;text-overflow:ellipsis;" title="${p.pname}">${p.pname}</td>

																	<td class="hidden-480" title="${p.pdate}">${p.pdate}</td>

																	<td>${p.pbrowse}</td>
																</tr>
															</c:forEach>
														</tbody>
													</table>
												</div><!-- /.widget-main -->
											</div>

											<div class="tab-pane" id="hot">
												<div class="widget-main no-padding">
													<table class="table table-bordered table-striped" style="table-layout:fixed">
														<thead class="thin-border-bottom">
														<tr>
															<th>
																<i class="ace-icon fa fa-caret-right blue"></i>商品图片
															</th>

															<th>
																<i class="ace-icon fa fa-caret-right blue"></i>商品名称
															</th>

															<th class="hidden-480">
																<i class="ace-icon fa fa-caret-right blue"></i>发布时间
															</th>

															<th>
																<i class="ace-icon fa fa-caret-right blue"></i>浏览量
															</th>
														</tr>
														</thead>

														<tbody>
															<c:forEach items="${hotestProducts}" var="p" end="4">
																<tr>
																	<td style="text-align: center;"><img width="32" src="${pageContext.request.contextPath}/${p.pimage}" alt="${p.pimage}"></td>
																	<td style="overflow:hidden;white-space:nowrap;text-overflow:ellipsis;" title="${p.pname}">${p.pname}</td>

																	<td class="hidden-480" title="${p.pdate}">${p.pdate}</td>

																	<td>${p.pbrowse}</td>
																</tr>
															</c:forEach>
														</tbody>
													</table>
												</div><!-- /.widget-main -->
											</div>
										</div>
									</div><!-- /.widget-body -->
								</div><!-- /.widget-box -->
							</div><!-- /.col -->

							<div class="col-sm-7">
								<div class="widget-box transparent">
									<div class="widget-header widget-header-flat">
										<h4 class="widget-title lighter">
											<i class="ace-icon fa fa-signal"></i>
											用户和购买力统计
										</h4>

										<div class="widget-toolbar">
											<a href="#" data-action="collapse">
												<i class="ace-icon fa fa-chevron-up"></i>
											</a>
										</div>
									</div>

									<div class="widget-body">
										<div class="widget-main padding-4">
											<div id="users-order-charts"></div>
										</div><!-- /.widget-main -->
									</div><!-- /.widget-body -->
								</div><!-- /.widget-box -->
							</div><!-- /.col -->
						</div><!-- /.row -->
						<!-- PAGE CONTENT ENDS -->
					</div><!-- /.col -->
				</div><!-- /.row -->
			</div><!-- /.page-content -->
		</div>
	</div><!-- /.main-content -->
	<!-- 向上按钮 -->
	<a href="#" id="btn-scroll-up" class="btn-scroll-up btn btn-sm btn-inverse">
		<i class="ace-icon fa fa-angle-double-up icon-only bigger-110"></i>
	</a>
</div><!-- /.main-container -->
</body>

<!-- inline scripts related to this page -->
<script type="text/javascript">
    // 异步请求到服务器的数据，以动画的方式填充到span中
    function req(url,id){
        $.get(url,function(data){
            var num = $(id);
            num.animate({count: data}, {
                duration: 1.5*1000, //持续时间
                step: function() {
                    num.text(Math.round(this.count));
                }
            });
            num.text(data);
        });
    }
    jQuery(function($) {

    	// 异步请求统计数据
        req("${pageContext.request.contextPath}/statistics?method=getProductCount","#productCount");
        req("${pageContext.request.contextPath}/statistics?method=getCategoryCount","#categoryCount");
        req("${pageContext.request.contextPath}/statistics?method=getUserCount","#userCount");
        req("${pageContext.request.contextPath}/statistics?method=getProductBrowseCount","#browseCount");
        req("${pageContext.request.contextPath}/statistics?method=getOrderCount","#orderCount");


        $('.sparkline').each(function(){
            var $box = $(this).closest('.infobox');
            var barColor = !$box.hasClass('infobox-dark') ? $box.css('color') : '#FFF';
            $(this).sparkline('html',
                {
                    tagValuesAttribute:'data-values',
                    type: 'bar',
                    barColor: barColor ,
                    chartRangeMin:$(this).data('min') || 0
                });
        });


        //flot chart resize plugin, somehow manipulates default browser resize event to optimize it!
        //but sometimes it brings up errors with normal resize event handlers
        $.resize.throttleWindow = false;

        var placeholder = $('#piechart-placeholder').css({'width':'90%' , 'min-height':'135px'});

        // 异步请求到饼图数据
	    $.ajax({
		    type : "post",
		    async : true,
		    url : "${pageContext.request.contextPath}/statistics",
		    data : {
			    method:"getCategoryProportion"
		    },
		    dataType : "json",
		    success : function(result) {
			    var labels = [];
			    var datas = [];
			    var colors = [];
			    var total = 0;

			    if (result) {
				    for(var i=0;i<result.length;i++){
					    labels.push(result[i].cname);
					    datas.push(result[i].productCount);
					    total += datas[i];
					    colors.push(randomColor());
				    }
			    }

			    console.log( labels.length);
			    var data = [];
			    for(var i = 0; i < labels.length; i++){
				    data.push({
					    "label":labels[i]+"/所有商品",
					    "data":(datas[i]/total),
					    "color":colors[i]
				    });
			    }

			    drawPieChart(placeholder, data);

			    placeholder.data('chart', data);
			    placeholder.data('draw', drawPieChart);
		    }
	    });

        // 画饼图
        function drawPieChart(placeholder, data, position) {
            $.plot(placeholder, data, {
                series: {
                    pie: {
                        show: true,
                        tilt:0.8,
                        highlight: {
                            opacity: 0.25
                        },
                        stroke: {
                            color: '#fff',
                            width: 2
                        },
                        startAngle: 2
                    }
                },
                legend: {
                    show: true,
                    position: position || "ne",
                    labelBoxBorderColor: null,
                    margin:[-30,15]
                }
                ,
                grid: {
                    hoverable: true,
                    clickable: true
                }
            });
        }

        // 随机颜色
	    function randomColor() {
		    return '#'+ Math.random().toString(16).slice(2,8);
	    }


        // pie chart tooltip example
        var $tooltip = $("<div class='tooltip top in'><div class='tooltip-inner'></div></div>").hide().appendTo('body');
        var previousPoint = null;

        placeholder.on('plothover', function (event, pos, item) {
            if(item) {
                if (previousPoint != item.seriesIndex) {
                    previousPoint = item.seriesIndex;
                    var tip = item.series['label'] + " : " + item.series['percent']+'%';
                    $tooltip.show().children(0).text(tip);
                }
                $tooltip.css({top:pos.pageY + 10, left:pos.pageX + 10});
            } else {
                $tooltip.hide();
                previousPoint = null;
            }
        });

        /////////////////////////////////////
        $(document).one('ajaxloadstart.page', function(e) {
            $tooltip.remove();
        });


        $('#users-order-charts').css({'width':'100%' , 'height':'220px'});
        var userchart = echarts.init(document.getElementById('users-order-charts'));
	    userchart.setOption({
            title : {
                text : ""
            },
            tooltip : {
                trigger : 'axis',
                showDelay : 0, // 显示延迟，添加显示延迟可以避免频繁切换，单位ms
                axisPointer : {            // 坐标轴指示器，坐标轴触发有效
                    type : 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                }
            },
            legend: {
                data:['订单数量'],
				x : '10%',
				y : 'top',
				top : '15%'
            },
            toolbox: {
                show : true,
                feature : {
                    mark : {show: true},
                    dataView : {show: true, readOnly: false},
                    magicType : {show: true, type: ['line', 'bar', 'stack', 'tiled']},
                    restore : {show: true},
                    saveAsImage : {show: true}
                },
            },
            calculable : true,
            xAxis : [
                {
                    type : 'value'
                }
            ],
            yAxis : [
                {
                    type : 'category',
                    data : [],
				}
            ],
            dataZoom: [
                {
                    type: 'slider',
                    show: true,
                    yAxisIndex: [0],
                    start: 0,
                    end: 40,
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '50%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                }
			],
            series : [
                {
                    name:'订单数量',
                    type:'bar',
                    stack: '总量',
                    itemStyle : { normal: {label : {show: true, position: 'insideRight'}}},
                    data:[]
                }
            ],
			color : ['#438eb9']
        });
        // 加载动画
	    userchart.showLoading();
        var names=[];    //类别数组（实际用来盛放Y轴坐标值）
        var orders=[];    //销量数组（实际用来盛放X坐标值）
		// 异步请求数据
        $.ajax({
            type : "post",
            async : true,
            url : "${pageContext.request.contextPath}/statistics",
            data : {
				method:"getUsersAndOrders"
            },
            dataType : "json",
            success : function(result) {
                // 请求成功时执行该函数内容，result即为服务器返回的json对象
                if (result) {
                    for(var i=0;i<result.length;i++){
                        names.push(result[i].username);
	                    orders.push(result[i].orderCount);
                    }
	                userchart.hideLoading();
	                userchart.setOption({
                        xAxis : [
                            {
                                type : 'value'
                            }
                        ],
                        yAxis : [
                            {
                                type : 'category',
                                data : names,
                            }
                        ],
                        series : [
                            {
                                name:'订单数量',
                                type:'bar',
                                stack: '总量',
                                itemStyle : { normal: {label : {show: true, position: 'insideRight'}}},
                                data:orders
                            }
                        ]
                    });

                }
            },
            error : function(errorMsg) {
                // 请求失败时执行该函数
                alert("图表数据加载失败!");
	            userchart.hideLoading();
            }
        });


        $('#recent-box [data-rel="tooltip"]').tooltip({placement: tooltip_placement});
        function tooltip_placement(context, source) {
            var $source = $(source);
            var $parent = $source.closest('.tab-content')
            var off1 = $parent.offset();
            var w1 = $parent.width();

            var off2 = $source.offset();
            //var w2 = $source.width();

            if( parseInt(off2.left) < parseInt(off1.left) + parseInt(w1 / 2) ) return 'right';
            return 'left';
        }


        $('.dialogs,.comments').ace_scroll({
            size: 300
        });


        //Android's default browser somehow is confused when tapping on label which will lead to dragging the task
        //so disable dragging when clicking on label
        var agent = navigator.userAgent.toLowerCase();
        if(ace.vars['touch'] && ace.vars['android']) {
            $('#tasks').on('touchstart', function(e){
                var li = $(e.target).closest('#tasks li');
                if(li.length == 0)return;
                var label = li.find('label.inline').get(0);
                if(label == e.target || $.contains(label, e.target)) e.stopImmediatePropagation() ;
            });
        }

        $('#tasks').sortable({
                opacity:0.8,
                revert:true,
                forceHelperSize:true,
                placeholder: 'draggable-placeholder',
                forcePlaceholderSize:true,
                tolerance:'pointer',
                stop: function( event, ui ) {
                    //just for Chrome!!!! so that dropdowns on items don't appear below other items after being moved
                    $(ui.item).css('z-index', 'auto');
                }
            }
        );
        $('#tasks').disableSelection();
        $('#tasks input:checkbox').removeAttr('checked').on('click', function(){
            if(this.checked) $(this).closest('li').addClass('selected');
            else $(this).closest('li').removeClass('selected');
        });


        //show the dropdowns on top or bottom depending on window height and menu position
        $('#task-tab .dropdown-hover').on('mouseenter', function(e) {
            var offset = $(this).offset();

            var $w = $(window)
            if (offset.top > $w.scrollTop() + $w.innerHeight() - 100)
                $(this).addClass('dropup');
            else $(this).removeClass('dropup');
        });

    })
</script>
</body>
</html>
